﻿using Host;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AXImServerConsole
{
    class Program
    {
        static void AddEnvironmentPaths(IEnumerable<string> paths)
        {
            var path = new[] { Environment.GetEnvironmentVariable("PATH") ?? string.Empty };
            string newPath = string.Join(Path.PathSeparator.ToString(), paths.Concat(path));
            Environment.SetEnvironmentVariable("PATH", newPath);
        }

        static void Main(string[] args)
        {
            //加载合适的相关内容
            AddEnvironmentPaths(new string[] { Path.Combine(Directory.GetCurrentDirectory(), "Hosts"), Directory.GetCurrentDirectory() });

            EventTools.GetInstance().TriggerEvent("LoadDll");
            EventTools.GetInstance().TriggerEvent("SystemStart");

            var hosts = SelfStartAssemblyHost.GetInstance().GetSelfStartHostInstance();
            foreach (var item in hosts)
            {
                HostManager.GetInstance().AddHost(item);
            }


            bool runing = true;

            var thread = new Thread(() =>
            {
                while (runing)
                {
                    HostManager.GetInstance().Update();
                    Thread.Sleep(HostManager.GetInstance().GetHostCount() > 0 ? 100 : 1000);
                }

                runing = false;
            });
            thread.IsBackground = true;
            thread.Start();

            EventTools.GetInstance().TriggerEvent("MainThreadStart");

            while (true)
            {
                string userinput = Console.ReadLine();

                if (userinput == "exit")
                {
                    break;
                }

                var func = UserInputHandleManager.GetInstance().GetHanlde(userinput);
                if (func != null)
                {
                    func();
                }
                else
                {
                    Console.WriteLine("Not Find Hanlde For " + userinput);
                }
            }

            EventTools.GetInstance().TriggerEvent("SystemWillStop");

            runing = false;
            while (thread.ThreadState == ThreadState.Running)
            {
                Thread.Sleep(100);
            }

            EventTools.GetInstance().TriggerEvent("SystemStop");
        }
    }
}
